package ln.fxspringarchetype.controller.student;

import javafx.beans.binding.Bindings;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.FileChooser;
import javafx.stage.Window;
import ln.fxspringarchetype.controller.BaseFxController;
import ln.fxspringarchetype.vo.StudentVO;

import java.io.*;
import java.net.URI;
import java.time.LocalDate;
import java.util.Objects;
import java.util.Random;

public class AddStudentController extends BaseFxController {
    /**
     * 默认图片的路径
     */
    private static final String default_photo_path = "/img/default-photo.jpg";
    /**
     * 默认图片对象
     */
    private static final File default_photo_file = new File(
            URI.create(String.valueOf(AddStudentController.class.getResource(default_photo_path))));
    /**
     * 表单对应的视图模型
     */
    private final StudentVO studentVO = new StudentVO();
    private final FileChooser fileChooser = new FileChooser();
    private final ObjectProperty<File> photoFileProperty = new SimpleObjectProperty<>();
    @FXML
    private ImageView photoView;
    @FXML
    private TextField nameField;
    @FXML
    private DatePicker birthdayPicker;
    @FXML
    private ChoiceBox<String> genderField;
    @FXML
    private Button photoButton;

    public StudentVO getStudentVO() {
        return studentVO;
    }

    @Override
    public void initLayout() {
        nameField.setText("学生姓名");
        genderField.getSelectionModel().selectFirst();
        birthdayPicker.setValue(LocalDate.now());
        fileChooser.setInitialDirectory(
                new File(URI.create(String.valueOf(getClass().getResource("/")))));
        photoFileProperty.setValue(default_photo_file);
    }

    @Override
    public void loadData() {
        studentVO.setId(new Random().nextInt(0, Integer.MAX_VALUE));
    }

    @Override
    public void setCellValueFactories() {

    }

    @Override
    public void setCellFactories() {

    }

    @Override
    public void createBindings() {
        studentVO.nameProperty().bind(nameField.textProperty());
        studentVO.genderProperty().bind(genderField.valueProperty());
        studentVO.birthdayProperty().bind(birthdayPicker.valueProperty());
        studentVO.photoProperty().bind(
                Bindings.createObjectBinding(
                        () -> {
                            byte[] bytes = new byte[0];
                            File file = photoFileProperty.getValue();
                            if (Objects.nonNull(file) && file.exists()) {
                                try {
                                    FileInputStream fileInputStream = new FileInputStream(file);
                                    bytes = fileInputStream.readAllBytes();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            return bytes;
                        }, photoFileProperty));
        photoView.imageProperty().bind(
                Bindings.createObjectBinding(
                        () -> {
                            InputStream inputStream;
                            byte[] bytes = studentVO.getPhoto();
                            if (Objects.nonNull(bytes)) {
                                inputStream = new ByteArrayInputStream(bytes);
                            } else {
                                inputStream = new ByteArrayInputStream(new byte[0]);
                            }
                            return new Image(inputStream);
                        }, studentVO.photoProperty()));
    }

    @FXML
    private void choosePhoto() {
        //选择照片对话框取消时，选定默认图片
        photoFileProperty.setValue(
                Objects.requireNonNullElse(
                        fileChooser.showOpenDialog(Window.getWindows().get(0)),
                        default_photo_file
                )
        );
    }
}
